package com.atguigu.daijia.customer.config;

import com.atguigu.daijia.common.util.AuthContextHolder;
import com.atguigu.daijia.common.util.IpUtil;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 山顶洞人郑某
 * @className LoginInterpecter.java 登录接口拦截器
 * @date 2024 09 04
 */
@Component
public class LoginInterpecter implements HandlerInterceptor {


  private CustomerLoginLogMapper customerLoginLogMapper;
  public LoginInterpecter(CustomerLoginLogMapper customerLoginLogMapper) {
      this.customerLoginLogMapper = customerLoginLogMapper;
  }
  //登录完成后记录登录用户日志
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      String ipAddress = IpUtil.getIpAddress(request);
      Long userId = AuthContextHolder.getUserId();
      CustomerLoginLog customerLoginLog = new CustomerLoginLog();
      customerLoginLog.setIpaddr(ipAddress);
      customerLoginLog.setMsg("用户登录");
      customerLoginLog.setCustomerId(userId);
      customerLoginLogMapper.insert(customerLoginLog);
      AuthContextHolder.removeUserId();
    }
}
